//
//  ReplyDetailVC.m
//  sensen_ios
//
//  Created by boye_mac1 on 16/3/31.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ReplyDetailVC.h"
#import "ReplyCell.h"
#import "ReplyCellFrameLayout.h"
@interface ReplyDetailVC ()<UITableViewDataSource, UITableViewDelegate>
{
    UITableView *_tableView; // 表视图
    NSUInteger _page;//页码
}
@property (nonatomic, strong) NSMutableArray *replyAry;
@end

@implementation ReplyDetailVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"回复";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBarButtonItemWithImagename:nil]; // 左侧返回按钮
    [self _createViews];
    [self _inData];
    // 下拉加载更多
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(_getMoreData)];
    _tableView.footer = footer;

    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.tabBarController;
    [main showTabBar];
}

#pragma mark 创建视图
- (void)_createViews {
    [self _initTableView];
}
// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // 注册单元格
    [_tableView registerClass:[ReplyCell class] forCellReuseIdentifier:@"ReplyCell"];
}
#pragma mark 数据
- (void)_inData{
    [SVProgressHUD showWithStatus:@"请耐心等待..."]; // 请求中
    if (_replyAry == nil) {
        _replyAry = [[NSMutableArray alloc] init];
    }else{
        [_replyAry removeAllObjects];
    }
    _page = 1;
    [self _getData];
}
- (void)_getMoreData{
    _page += 1;
    [self _getData];
}
- (void)_getData {
//    [SVProgressHUD showWithStatus:@"请耐心等待..."]; // 请求中
    self.view.userInteractionEnabled = NO;
    NSDictionary *params;
    NSString *pagesize = @"10";
    NSString *curpage = [NSString stringWithFormat:@"%ld",(unsigned long)_page];
    params = @{@"tid" : _tid, @"pid" : _pid ,@"pagesize" : pagesize , @"curpage" : curpage };
    [BoyeHttpClient post:@"BY_ForumPost_commentQuery" apiVerson:100 params:params  success:^(AFHTTPRequestOperation *operation, id result) {
        if(![result[@"list"] isKindOfClass:[NSNull class]]){
        NSArray *array = result[@"list"];
        NSString *nub = result[@"count"];
        NSInteger nubInt = [nub intValue];
        for (NSDictionary *resultDic in array) {
            ReplyCellFrameLayout *layout = [[ReplyCellFrameLayout alloc] init];
            ReplyModel *model = [[ReplyModel alloc] initContentWithDic:resultDic];
            layout.model = model;
            [_replyAry addObject:layout];
        }
        [_tableView reloadData];
        [_tableView.footer endRefreshing];
        if (_replyAry.count == nubInt) {
            [_tableView.footer removeFromSuperview];
        }
        }
        [SVProgressHUD dismiss];
        self.view.userInteractionEnabled = YES;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        self.view.userInteractionEnabled = YES;
        NSLog(@"%@",error);
        [SVProgressHUD dismiss];
        [SVProgressHUD showErrorWithStatus:@"加载失败" withDuration:1];
    }];
}

#pragma mark 表视图代理
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _replyAry.count;
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ReplyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ReplyCell"];
    if (cell == nil) {
        cell = [[ReplyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ReplyCell"];
    }
    ReplyCellFrameLayout *layout = _replyAry[indexPath.row];
    cell.layout = layout;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if ([_auId integerValue] == [layout.model.author_id integerValue]) {
        cell.louLabel.hidden = NO;
    }else{
        cell.louLabel.hidden = YES;
    }
    return cell;
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    ReplyCellFrameLayout *layout = _replyAry[indexPath.row];
    return layout.cellRect.size.height;
}
// 设置组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 1;
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 1;
}

// 分割线距离左边距离
-(void)viewDidLayoutSubviews
{
    if ([_tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [_tableView setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([_tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [_tableView setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UserModel *user = [CommonCache getUserInfo];
    ReplyCellFrameLayout *layout = _replyAry[indexPath.row];
    __weak typeof (self) weakSelf = self;
    if ((user.uid == layout.model.author_id)||([user.allowdelpost intValue] == 1)) {
        NSDictionary *params = @{@"tid":_tid,@"uid":user.uid,@"pid":_pid,@"id":layout.model.replyId};
        if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
            
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"确定删除回复吗" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [BoyeHttpClient post:@"BY_ForumPost_DeleteComment" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
                    [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
                    [weakSelf _inData];
                    [_tableView reloadData];
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"%@",error);
                    [SVProgressHUD showErrorWithStatus:@"删除失败，请重试" withDuration:1];
                }];
            }];
            [alertController addAction:cancelAction];
            [alertController addAction:okAction];
            [self presentViewController:alertController animated:YES completion:nil];
            
        }else{
            [BoyeHttpClient post:@"BY_ForumPost_DeleteComment" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
                [SVProgressHUD showSuccessWithStatus:@"删除成功" withDuration:1];
                [weakSelf _inData];
                [_tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD dismiss];
                [SVProgressHUD showErrorWithStatus:@"删除失败，请重试" withDuration:1];
            }];
            
        }

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
